package framework.server;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

import org.apache.log4j.Logger;

import common.LogCategory;

import framework.Admin;

/**
 * The admin of the framework
 *
 * @author	Orlin Tomov
 * @version	0.2
 *
 */
public class AdminImpl extends UnicastRemoteObject implements Admin {

	/**
	 * 
	 */
	private static final Logger log = LogCategory.getCategory(AdminImpl.class);
	private static final long serialVersionUID = 1L;
	private Server server;
	String echo;

	/**
	 * Construct the admin
	 *
	 * @param	server	the framework for admin
	 */
	AdminImpl(Server server) throws RemoteException {
		this.server = server;
	}

	/**
	 * Executes a command and returns the result
	 *
	 * @param	command	the command for execute
	 * @return	the result of executed command
	 */
	@Override
	public String command(String command) throws RemoteException {
		echo = "?";
		CommandThread commandthread = new CommandThread(server, this, command);
		commandthread.start();
		while (true) {
			synchronized (echo) {
				if (!echo.equalsIgnoreCase("?")) {
					//server = null;
					return echo;
				}
			}
		}
	}

	class CommandThread extends Thread {

		private Server server = null;
		private String command = null;
		private AdminImpl admin = null;

		public CommandThread(Server server, AdminImpl admin, String command) {
			this.server = server;
			this.command = command;
			this.admin = admin;
		}

		public void run() {
			try  {
				String echo = server.command(command);
				synchronized(admin.echo) {
					admin.echo = echo;
				}
				//server = null;
				//admin = null;
				return;
			} catch (Exception exception) {
				/**/log.error("Could not send command to server due to:", exception);
				return;
			}
		}
	}
}
